<?php
/**
 * 设计师大赛最终奖项荣誉控制器
 */
namespace Beerus\Modules\DesignerCompetition\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\ReDesignerCompetition\DcHonor;
use Doraemon\model\Totem\Totems;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class HonorController extends Controller
{
    const PAGE_SIZE = 15;
    const HONOR_TYPE_LIST = [
        DcHonor::HONOR_TYPE_GOLD => '金奖',
        DcHonor::HONOR_TYPE_SLIVER => '银奖',
        DcHonor::HONOR_TYPE_BEST => '最佳',
        DcHonor::HONOR_TYPE_WIN => '优胜',
        DcHonor::HONOR_TYPE_TOP => 'top奖项',
        DcHonor::HONOR_TYPE_PEOPLE => '人员奖',
        DcHonor::HONOR_TYPE_OTHER => '其他'
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    // 设计师大赛奖项列表
    public function index(Request $request, Content $content)
    {
        $request_params = $request->all();

        $pageSize = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition = [];
        if (!empty($request_params['id'])) {
            $condition['id'] = $request_params['id'];
        }
        if (!empty($request_params['honor_year'])) {
            $condition['honor_year'] = $request_params['honor_year'];
        }
        if (!empty($request_params['honor_type'])) {
            $condition['honor_type'] = $request_params['honor_type'];
        }
        $condition['data_status'] = DcHonor::STATUS_NORMAL;
        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $pageSize,
            $pageSize,
        ];
        $tips = [];
        return $content
            ->header('评选奖项管理')
            ->row($tips)
            ->row($this->indexGrid($condition, $pageSize));
    }

    /**
     * 表格展示部分
     * @param $condition
     * @return Grid
     */
    public function indexGrid($condition, $pageSize)
    {
        $lists = DcHonor::select('*', $condition);

        unset($condition['ORDER']);
        unset($condition['LIMIT']);

        $total = DcHonor::count($condition);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $pageSize
        ]);

        $search_params = http_build_query($condition);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params) {
                $grid->setActionClass(DropdownActions::class);
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('id', '奖项ID')->placeholder('请输入奖项ID');
                        $filter->equal('honor_type', '奖项类型')->select(self::HONOR_TYPE_LIST);
                    });
                    $filter->year('honor_year', '奖项年份');
                    $filter->expand();
                });
                $grid->column('id', '奖项id');
                $grid->column('honor_name', '奖项名称');
                $grid->column('honor_sub_name', '奖项子名称');
                $grid->column('honor_year', '奖项年份');
                $grid->column('honor_type', '奖项类型')->display(function () {
                    return self::HONOR_TYPE_LIST[$this->honor_type];
                });
                $grid->column('honor_num', '奖项个数');
                $grid->column('main_show_sort', '奖项主排序');
                $grid->column('sub_show_sort', '奖项子排序');
                $grid->column('totem_name', '徽章名称')->display(function () {
                    $totemName = '';
                    if ($this->totem_id) {
                        $totemData = Totems::getNormalTotemById($this->totem_id);
                        $totemName = $totemData['totem_name'];
                    }
                    return $totemName;
                });
            }
        );
        return $gridList;
    }

    // 新增/修改奖项信息
    public function edit(Request $request, Content $content, $id = 0) {
        $request = $request->all();

        if ($id == 0) {
            $is_create = true;
            $header = '新增';
        } else {
            $is_create = false;
            $header = '修改';
        }

        $tab = new Tab();
        $tab->add('奖项信息', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => '设计师奖项列表',
                'url' => route('honor.list')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        if ($isCreate) {
            $data = [];
            $form = new Form($data);
        } else {
            $data = DcHonor::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->text('id', '奖项ID')->readOnly();
        }

        $form->text('honor_name', '奖项名称')->required('不能为空');
        $form->text('honor_sub_name', '奖项从属名称');
        $form->select('honor_type', '奖项类型')->options(self::HONOR_TYPE_LIST)->required();
        $form->text('totem_id', '徽章ID');
        $form->year('honor_year', '奖项年份')->default(date('Y'));
        $form->number('honor_num', '奖项数')->default(1)->min(1);
        $form->text('main_show_sort', '主排序');
        $form->text('sub_show_sort', '子排序');

        $form->action('/admin/DesignerCompetition/honor/save');
        return $form->render();
    }

    // 编辑奖项
    public function editSubmit(Request $request)
    {
        $request = $request->all();
        $data = [
            'honor_name' => $request['honor_name'],
            'honor_sub_name' => $request['honor_sub_name'],
            'honor_year' => $request['honor_year'],
            'totem_id' => $request['totem_id'],
            'honor_type' => $request['honor_type'],
            'honor_num' => $request['honor_num'],
            'main_show_sort' => $request['main_show_sort'],
            'sub_show_sort' => $request['sub_show_sort'],
        ];
        $cur_time = time();
        if (isset($request['id'])) {
            $data['edit_time'] = $cur_time;
            $rs = DcHonor::update($data, ['id' => $request['id']]);
        } else {
            $item = DcHonor::getItemByNameAndYear($request['honor_name'], $request['honor_year'], $request['honor_type'], $request['honor_sub_name']);
            if (!empty($item)) {
                $error = new MessageBag(['title' => '已存在同名奖项']);
                return back()->with(compact('error'));
            }
            $data['add_time'] = $cur_time;
            $rs = DcHonor::addInfo($data);
        }
        $title = isset($request['id']) ? '修改成功' : '添加成功';
        if (!$rs) {
            $error = new MessageBag(['title' => $title]);
            return back()->with(compact('error'));
        }
        $success = new MessageBag(['title' => $title]);
        return redirect('/admin/DesignerCompetition/honor')->with(compact('success'));
    }

    // 删除奖项
    public function del($id) {
        $honor = DcHonor::getItemById($id);
        if ($honor) {
            // 确认当前奖项是否有作品绑定
            $data['data_status'] = DcHonor::STATUS_DELETE;
            $data['edit_time'] = time();
            $rs = DcHonor::update($data, ['id' => $id]);
            if ($rs) {
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);
            }
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        return response()->json([
            'status' => false,
            'message' => "操作失败",
        ]);
    }
}
